package com.scau.common.annotations.resovler;

import com.scau.common.annotations.CurrentUser;
import com.scau.common.constants.HttpCode;
import com.scau.common.exception.StatusException;
import com.scau.entity.Admin;
import com.scau.entity.Counselor;
import com.scau.util.SessionUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class CurrentUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();

        String address = SessionUtil.getIpAddr(request);

        CurrentUser currentUser = methodParameter.getParameterAnnotation(CurrentUser.class);

        if (currentUser.type().equals(CurrentUser.Type.ADMIN)) {
            Admin admin = SessionUtil.getAdmin(address);

            if (admin == null) {
                throw new StatusException(HttpCode.Error.NOT_LOGINED);
            }
            return admin;
        } else if (currentUser.type().equals(CurrentUser.Type.COUNSELOR)) {
            Counselor counselor = SessionUtil.getCounselor(address);

            if (counselor == null) {
                throw new StatusException(HttpCode.Error.NOT_LOGINED);
            }

            return counselor;
        }

        throw new StatusException(HttpCode.Error.NOT_LOGINED);
    }
}
